package com.ds.infrastructure.hyperspace.console.model.request.deploy.deploydata;

import com.ds.infrastructure.hyperspace.console.dto.deploydata.HostDTO;
import com.ds.infrastructure.hyperspace.console.dto.deploydata.HostGroupDTO;
import com.ds.infrastructure.hyperspace.console.utils.ValidationUtil;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yaozhendong
 * @create: 2019-10-21 10:48
 **/
@Data
@NoArgsConstructor
public class HostGroupForm {
    @NotBlank
    private String id;
    @NotBlank
    private String groupName;
    private List<HostForm> hosts;

    public static HostGroupDTO toDTO(HostGroupForm item) {
        HostGroupDTO hostGroupDTO = new HostGroupDTO();
        hostGroupDTO.setId(item.getId());
        hostGroupDTO.setGroupName(item.getGroupName());
        addHostsDTO(item, hostGroupDTO);
        return hostGroupDTO;

    }

    private static void addHostsDTO(HostGroupForm form, HostGroupDTO hostGroupDTO) {
        if (form.getHosts() == null || form.getHosts().isEmpty()) {
            return;
        }
        ValidationUtil.validateEntityList(form.getHosts(), "hosts");
        List<HostDTO> hostDTOList = new ArrayList<>();
        form.getHosts().forEach(item -> hostDTOList.add(HostForm.toDTO(item)));
        hostGroupDTO.setHosts(hostDTOList);
    }

    public static HostGroupForm toVO(HostGroupDTO dto) {
        HostGroupForm hostGroupForm = new HostGroupForm();
        hostGroupForm.setId(dto.getId());
        hostGroupForm.setGroupName(dto.getGroupName());
        addHostsForm(dto, hostGroupForm);
        return hostGroupForm;
    }

    private static void addHostsForm(HostGroupDTO dto, HostGroupForm form) {
        if (dto.getHosts() == null || dto.getHosts().isEmpty()) {
            return;
        }
        List<HostForm> hostFormList = new ArrayList<>();
        dto.getHosts().forEach(item -> hostFormList.add(HostForm.toVO(item)));
        form.setHosts(hostFormList);
    }
}
